package cn.vshare.controller;

import cn.vshare.entity.Footprint;
import cn.vshare.entity.Kind;
import cn.vshare.entity.User;
import cn.vshare.entity.Video;
import cn.vshare.service.FootprintService;
import cn.vshare.service.KindService;
import cn.vshare.service.VideoService;
import cn.vshare.util.DateUtil;
import cn.vshare.util.VideoUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageInfo;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.json.MappingJackson2JsonView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.websocket.OnClose;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;


@RestController
@ServerEndpoint("/upload")
public class VideoController {
    public static Map<String, Session> sessionMap = new HashMap<>();
    private String sessionId;
    private VideoUtil videoUtil;

    @Resource(name = "videoServiceImpl")
    private VideoService videoService;

    @Resource
    private KindService kindService;

    @Resource
    private FootprintService footprintService;

    @RequestMapping("uploadVideo")
    public Video uploadVideo(String sessionId, Video video, MultipartFile file, HttpServletRequest request) {

        System.out.println(sessionId);
        System.out.println(sessionId);
        String videoUtilId = UUID.randomUUID().toString();
        Map map = videoService.createVideo(videoUtilId, video, file, request);
        Session session = (Session) sessionMap.get(sessionId);
        int totalTime = 1;
        int currTime = 1;
        String finish = "no";
        while ("no".equals(finish)) {
            try {
                Thread.sleep(1 * 1000);
                Object videoUtilstr = VideoUtil.currTimeMap.get(videoUtilId);
                if (videoUtilstr != null) {
                    videoUtil = (VideoUtil) videoUtilstr;
                    totalTime = Integer.parseInt(videoUtil.getTotalTime());
                    System.out.println("111111111111111111111" + totalTime);
                    currTime = Integer.parseInt(videoUtil.getCurrTime());
                    System.out.println("111111111111111111111" + currTime);
                    finish = videoUtil.getFinish();
                    System.out.println("111111111111111111111" + finish);
                    if (session.isOpen()) {
                        session.getBasicRemote().sendText(totalTime + "," + currTime + "," + finish);
                    }
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        VideoUtil.currTimeMap.remove(videoUtilId);
        map.remove(sessionId);
        Video video1 = (Video) map.get("video");
        videoService.addVideo(video1);
        return video1;
    }

    @OnOpen
    public void onOpen(Session session) {
        sessionId = UUID.randomUUID().toString();
        sessionMap.put(sessionId, session);
        try {
            session.getBasicRemote().sendText("id," + sessionId);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @OnClose
    public void onClose(Session session) throws IOException {
        session.close();
        System.out.println("上传连接关闭");
    }


    /**
     * 该方法用来像前台传送视频信息
     *
     * @param kind     类别
     * @param pageSize 每页显示条数
     * @param pageNo   当前页码
     * @return
     */
    @RequestMapping("queryVideoByKind")
    public Map<String, Object> queryVideoByKind(Kind kind, int pageSize, int pageNo) {
        Map<String, Object> cond = new HashMap<>();
        cond.put("kind", kind);
        cond.put("pageSize", pageSize);
        cond.put("pageNo", pageNo);

        Page<Video> page = videoService.queryVideoByKindId(cond);
        cond.put("page", page);
        cond.put("totalpages", page.getPages());
        return cond;
    }

    /**
     * 分类查询视频
     *
     * @param kind
     * @param pageSize
     * @param pageNo
     * @return
     * @author penghaixin
     */
    @RequestMapping("/getVideosByKindId")
    public Map<String, Object> getVideosByKindId(Kind kind, int pageSize, int pageNo) {
        Map<String, Object> cond = new HashMap<>();
        cond.put("kind", kind);
        cond.put("pageSize", pageSize);
        cond.put("pageNum", pageNo);
        Page<Video> page = videoService.getVideoByUpTimeAndName(cond);
        cond.put("page", page);
        cond.put("totalpages", page.getPages());
        cond.put("totalRows", page.getTotal());
        return cond;
    }


    @RequestMapping("/toList")
    public ModelAndView toList() {
        return new ModelAndView("h-ui/video-list");
    }

    @RequestMapping("/delVideo")
    public ModelAndView delVideo() {
        return new ModelAndView("h-ui/del-video");
    }

    @RequestMapping("/getVideoByUpTimeAndName")
    public Map getVideoByUpTimeAndName(String startTime, String endTime, String name, int pageSize, int pageNum, String lipin1) {
        Map map = new HashMap();
        map.put("startTime", startTime);
        map.put("endTime", endTime);
        map.put("name", name);
        map.put("pageSize", pageSize);
        map.put("pageNum", pageNum);
        map.put("isForbidden", lipin1);
        Page page = videoService.getVideoByUpTimeAndName(map);
        map.put("page", page);
        map.put("totalPage", page.getPages());
        map.put("totalRow", page.getTotal());//总条数
        //测试
        System.out.println(JSON.toJSONString(map));
        return map;
    }

    /* @RequestMapping("/getLikeVideos")
     public ModelAndView getLikeVideos(String cond){
         ModelAndView mv = new ModelAndView();
         List<Video> list = videoService.getLikeVideos(cond);
         mv.addObject("list",list);
         mv.setViewName("searchVideo");
         return mv;
     }*/
    @RequestMapping("/getLikeVideos")
    public ModelAndView getLikeVideos(Integer pageSize, Integer pageNum, String search) {
        if (pageSize == null) {
            pageSize = 8;
        }
        if (pageNum == null) {
            pageNum = 1;
        }
        Map<String, Object> cond = new HashMap<>();
        ModelAndView mv = new ModelAndView();
        cond.put("pageSize", pageSize);
        cond.put("pageNum", pageNum);
        cond.put("search", search);
        Page page = videoService.getLikeVideos(cond);
        cond.put("total", page.getTotal());
        cond.put("page", page);
        System.out.println(JSON.toJSONString(page));
        cond.put("totalPage", page.getPages());
        cond.put("totalPage", page.getPages());
        mv.addObject("cond", cond);
        mv.setViewName("searchVideo");
        return mv;
    }


    @RequestMapping("/getKindVideos")
    public ModelAndView getKindVideos(Kind kind1) {
        Kind kind = kindService.queryKind(kind1);//通过前台传来的kind_id 查询完整kind信息
        ModelAndView mv = new ModelAndView("querykindVideos");
        mv.addObject("kind", kind);
        return mv;
    }

    @RequestMapping("/getVideos")
    public ModelAndView getVideos(Integer pageSize, Integer pageNum, String search) {
        if (pageSize == null) {
            pageSize = 5;
        }
        if (pageNum == null) {
            pageNum = 1;
        }
        Map<String, Object> cond = new HashMap<>();
        ModelAndView mv = new ModelAndView();
        mv.setView(new MappingJackson2JsonView());
        cond.put("pageSize", pageSize);
        cond.put("pageNum", pageNum);
        cond.put("search", search);
        Page<Video> page = videoService.getLikeVideos(cond);
        cond.put("totalPage", page.getPages());
        cond.put("total", page.getTotal());
        cond.put("page", page);

        mv.addObject("cond", cond);
        return mv;
    }

    @RequestMapping("queryVideoByUserId")
    public PageInfo queryVideoByUserId(int pageNum, int pageSize, String userId) {
        Page<Video> page = videoService.queryVideoByUserId(pageNum, pageSize, userId);
        PageInfo<Video> pageInfo = new PageInfo<>(page);
        return pageInfo;
    }

    @RequestMapping("getVideosByUserIdKinId")
    public PageInfo<Video> getVideosByUserIdKinId(String userId, String kindId, int pageSize, int pageNum) {
        Page<Video> page = videoService.getVideosByUserIdKinId(userId, kindId, pageSize, pageNum);
        return new PageInfo<>(page);
    }


    @RequestMapping("/countVideo")
    public Map<String, Object> countVideo() {
        Map<String, Object> map = new HashMap<String, Object>();
        List<Kind> kindList = kindService.queryAllKind(); //获取所有视频种类
        for (Kind kind : kindList) {
            int viewTimes = videoService.countVideoTypeByKind(kind); //获取每种视频的数目
            map.put(kind.getName(), viewTimes); //将视频种类和观看次数对应封装
        }
        return map;
    }

    @RequestMapping("/getViewTimes")
    public Map<String, Object> getViewTimes() {
        Map<String, Object> map = new HashMap<String, Object>();
        List<Kind> kindList = kindService.queryAllKind(); //获取所有视频种类
        for (Kind kind : kindList) {
            int viewTimes = videoService.countViewTimesByKind(kind); //获取每种视频的观看次数
            map.put(kind.getName(), viewTimes); //将视频种类和观看次数对应封装
        }
        return map;
    }

    /**
     * 通过年龄段统计不同年龄段视频量
     *
     * @param ages
     * @return
     * @author penghaixin
     */
    @RequestMapping("/countVideoByAges")
    public Map<String, Object> countVideoByAges(String ages) {
        Map<String, Object> map = new HashMap<String, Object>();
        JSONArray jsonArray = JSON.parseArray(ages); //将字符串转成JSON数组
        for (int i = 0; i < jsonArray.size(); i++) {
            JSONObject jsonObject = JSONObject.parseObject(jsonArray.get(i).toString()); //将JSON数组的字符串转换成JSON对象
            int videoNum = videoService.countVideoByAge(jsonObject);//统计各年龄段的视频上传量
            map.put(jsonObject.get("ageRange").toString(), videoNum);
        }
        return map;
    }

    /**
     * 播放视频
     *
     * @param vid
     * @return
     */

    @RequestMapping("/queryVideoByvid")
    public ModelAndView queryVideoByvid(String vid, HttpSession session) {
        videoService.updatePageview(vid);//视频点击量
        Video video = videoService.queryVideoById(vid);
        User user = (User) session.getAttribute("USER");
        if (user != null) {
            String currtime = DateUtil.getCurrDate();//获取当前时间
            Footprint footprint = new Footprint();
            footprint.setFootprintDate(currtime);//设置播放时间
            footprint.setVideo(video);
            footprint.setUser(user);
            footprintService.writeFootprint(footprint);//向足迹表中写入数据
        }
        ModelAndView mv = new ModelAndView("videoPlayer");
        mv.addObject("video", video);
        return mv;
    }

    @RequestMapping("/getVideoById")
    public ModelAndView getVideoById(String id) {
        ModelAndView mv = new ModelAndView();
        Video video = new Video();
        video = videoService.getVideoById(id);
        System.out.println("aaaaaaaaaaaa" + JSON.toJSONString(video));
        mv.addObject("video", video);
        mv.setViewName("editVideo");
        return mv;
    }

    @RequestMapping("/getVideosById")
    public ModelAndView getVideosById(String id) {
        ModelAndView mv = new ModelAndView();
        Video video = new Video();
        video = videoService.getVideoById(id);
        mv.addObject("video", video);
        return mv;
    }

    @RequestMapping("/updateVideoById")
    public String updateVideoById(String id, String status) {
        videoService.updateVideoById(id, status);
        return "success";
    }

    @RequestMapping("/updateHYById")
    public String updateHYById(String id, String status) {
        videoService.updateVideoById(id, status);
        return "success";
    }

    @RequestMapping("/updateVideo")
    public String updateVideo(Video video) {
        videoService.updateVideo(video); //执行更新方法
        return "success";
    }

    /**
     * 通过userid kindid title动态查询视频
     * @param video
     * @param pageSize
     * @param pageNum
     * @return
     */
    @RequestMapping("/getVideosByUserIdKindIdTitle")
    public PageInfo<Video> getVideosByUserIdKindIdTitle(Video video, int pageSize, int pageNum) {
        return videoService.getVideosByUserIdKindIdTitle(video, pageSize, pageNum);
    }


    public VideoService getVideoService() {
        return videoService;
    }

    public void setVideoService(VideoService videoService) {
        this.videoService = videoService;
    }
}
